<template>
    <a-dropdown placement="bottomRight">
        <div class="cursor-pointer"> {{ userStore.name }} <caret-down-outlined /></div>
        <template #overlay>
            <a-menu>
                <a-menu-item @click="showModifyPasswordModal"> 修改密码 </a-menu-item>
                <a-menu-divider />
                <a-menu-item @click="logout"> 退出登录 </a-menu-item>
            </a-menu>
        </template>
    </a-dropdown>
    <a-modal v-model:visible="modifyPasswordModalVisible" title="修改密码" @cancel="handleClose" @ok="handleConfirm">
        <a-form ref="formRef" :label-col="labelCol" :wrapper-col="wrapperCol" :model="passwordForm" :rules="rules">
            <a-form-item label="原密码" name="oldPassword">
                <a-input-password v-model:value="passwordForm.oldPassword" />
            </a-form-item>
            <a-form-item label="新密码" name="newPassword">
                <a-input-password v-model:value="passwordForm.newPassword" />
            </a-form-item>
            <a-form-item label="确认新密码" name="confirmPassword">
                <a-input-password v-model:value="passwordForm.confirmPassword" />
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script setup lang="ts">
    import type { FormInstance } from 'ant-design-vue'
    import { message } from 'ant-design-vue'
    import { CaretDownOutlined } from '@ant-design/icons-vue'
    import { useUserStore } from '@/store/modules/user'
    import { useRouter } from 'vue-router'
    import { ROUTER_NAME } from '@/constant'
    import { reactive, ref } from 'vue'
    import { RuleObject } from 'ant-design-vue/es/form'
    import md5 from 'js-md5'
    import { updatePassword } from '@/apis/sys/user'

    const userStore = useUserStore()
    const router = useRouter()
    const logout = () => {
        userStore.logout()
        router.push({
            name: ROUTER_NAME.PAGE_LOGIN
        })
    }

    const modifyPasswordModalVisible = ref<boolean>(false)
    const labelCol = { style: { width: '8em' } }
    const wrapperCol = { span: 16 }
    const passwordForm = reactive({
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
    })
    const formRef = ref<FormInstance>()
    const isPasswordRegExp = (value: string) => {
        const passwordPattern = /^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$).{6,20}$/
        return passwordPattern.test(value)
    }
    let validatePass = async (_rule: RuleObject, value: string) => {
        if (value === '') {
            return Promise.reject('请输入新密码')
        } else if (value.length < 6 || value.length > 20) {
            return Promise.reject('密码长度6-20个字符')
        } else if (!isPasswordRegExp(value)) {
            return Promise.reject('字母（区分大小写）、数字、特殊字符两种及以上')
        } else {
            if (passwordForm.confirmPassword !== '') {
                formRef.value?.validateFields('confirmPassword')
            }
            return Promise.resolve()
        }
    }
    let validateConfirmPass = async (_rule: RuleObject, value: string) => {
        if (value === '') {
            return Promise.reject('请输入确认新密码')
        } else if (value !== passwordForm.newPassword) {
            return Promise.reject('两次输入密码不一致，请重新输入')
        } else {
            return Promise.resolve()
        }
    }
    const rules = {
        oldPassword: [{ required: true, trigger: 'change' }],
        newPassword: [{ required: true, validator: validatePass, trigger: 'change' }],
        confirmPassword: [{ required: true, validator: validateConfirmPass, trigger: 'change' }]
    }
    const showModifyPasswordModal = () => {
        modifyPasswordModalVisible.value = true
    }
    const handleClose = () => {
        formRef.value?.resetFields()
    }
    const handleConfirm = () => {
        formRef.value?.validateFields().then(() => {
            const params = {
                mobile: `${userStore.username}`,
                oldPassword: md5(passwordForm.oldPassword),
                password: md5(passwordForm.newPassword)
            }
            updatePassword(params).then(() => {
                message.success('密码修改成功')
                modifyPasswordModalVisible.value = false
                userStore.logout()
                router.push({ name: ROUTER_NAME.PAGE_LOGIN })
            })
        })
    }
</script>
